package Z.dailyExercise._0222;

public class _剑指Offer58I翻转单词顺序 {

    public static void main(String[] args) {
        _剑指Offer58I翻转单词顺序 test = new _剑指Offer58I翻转单词顺序() ;
        String s = "  hello world!  ";
       // System.out.println(s.trim());
        System.out.println(test.reverseWords("  hello world!  "));
    }
    public String reverseWords(String s) {
        if (s.length() == 0){
            return s;
        }
        s = s.trim();
        StringBuilder res = new StringBuilder();
        int end =0;
        int start =0;
        boolean flag =true;//表示start要复制
        for (int i=s.length()-1;i>=0;i--){
            if (flag){
                start =i;
                flag = false;
            }

            if (s.charAt(i)==' '){
                end = i+1;
                res.append(s, end, start+1);
                res.append(' ');
                flag = true;

                while (s.charAt(i)==' '){
                    i--;
                }
                i++;//for里面还要再减一次
            }

        }

        res.append(s,0,start+1);
        return res.toString();

    }
}
